//
//  PKRequestManager.m
//  PianKe
//
//  Created by lanou on 15/9/26.
//  Copyright (c) 2015年 徐永祥. All rights reserved.
//

#import "PKRequestManager.h"

@implementation PKRequestManager
-(void)requestWithType:(RequestType)type urlString:(NSString *)urlStr parDic:(NSDictionary *)parDic finish:(RequestFinish )finish error:(RequestError)error
{

    NSURL * url = [NSURL URLWithString:urlStr];
//    创建可变的请求方式
    NSMutableURLRequest * request =[NSMutableURLRequest requestWithURL:url];
//    如果是POST请求需要设置参数和请求方式
    
    if (type == POST) {
//        设置请求方式
        [request setHTTPMethod:@"POST"];
//        设置请求参数的Body体
        if (parDic.count >0) {
            [request setHTTPBody:[self parDicToDataWithDic:parDic]];

        }
        
          }
    [NSURLConnection sendAsynchronousRequest:request queue:([NSOperationQueue currentQueue]) completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
           finish(data);
        
        }
        else{
           error(connectionError);
        }
    }];
    
}
//把参数字典装换为POST请求所需要的参数体
-(NSData *)parDicToDataWithDic:(NSDictionary *)dic
{
    NSMutableArray * array = [NSMutableArray arrayWithCapacity:0];
//    遍历字典得到每一个键，得到所有的key=value类型的字符串
    for (NSString * key in dic) {
        NSString * str = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        [array addObject:str];
    }
//    数组里所有的key=value的字符串通过&符号链接
  NSString * string = [array componentsJoinedByString:@"&"];
    return [string dataUsingEncoding:NSUTF8StringEncoding];
}
+(void)requestWithType:(RequestType)type urlString:(NSString *)urlStr parDic:(NSDictionary *)parDic finish:(RequestFinish )finish error:(RequestError)error
{

    PKRequestManager * pkRequestManager = [[PKRequestManager alloc]init];
    return [pkRequestManager requestWithType:type urlString:urlStr parDic:parDic finish:finish error:
            error];
    
}


@end
